package com.anche.cywebnew.Controller.systemManager;

import com.anche.cywebnew.Service.systemManager.RoleResourceService;
import com.anche.cywebnew.Utils.Shiro.ShiroRealm;
import com.anche.cywebnew.Utils.annotation.OptLog;
import com.anche.cywebnew.Utils.enums.OptType;
import com.anche.cywebnew.Utils.result.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/roleResource")
public class RoleResourceController {

    private static final Logger logger = LoggerFactory.getLogger(RoleResourceController.class);

    @Autowired
    private RoleResourceService roleResourceService;

    @GetMapping("/resourceIdList")
    public Object getRoleResourceList(@RequestParam("roleId") String roleId) {
        try {
            List<String> stringList = roleResourceService.getRoleResourceList(roleId);
            logger.info("<查询角色ID为[{}]的所属资源成功>", roleId);
            return ResultUtil.success(stringList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("<查询角色ID为[{}]的所属资源异常>:{}", roleId, e);
            return ResultUtil.error(0, e.getMessage());
        }
    }

    @PostMapping("/resourceIdList")
    @ResponseBody
    @OptLog(title = "修改角色权限信息", type = OptType.UPDATE)
    public Object setResourceIdList(@RequestParam("resourceId") String resourceId, @RequestParam("roleId") String roleId) {
        try {
            roleResourceService.setResourceIdList(roleId, resourceId);
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            ShiroRealm realm = (ShiroRealm) rsm.getRealms().iterator().next();
            realm.clearAuthz();
            logger.info("刷新shiro缓存权限成功");
            return ResultUtil.success("修改角色权限成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(0, e.getMessage());
        }
    }
}

